//
//  GLLiveStreamBottomBar.swift
//  GLUZSwift
//
//  Created by yu on 2025/3/28.
//

import Foundation


@objc public enum GLLiveStreamBottomBarButtonName: Int {
//    /// IM 消息
//    case messageButton
    /// 申请连麦
    case coHostControlButton
    /// 摄像头开关
    case toggleCameraButton
    /// 麦克风开关
    case toggleMicrophoneButton
    /// 切换摄像头
    case switchCameraButton
    /// 购物车
    case shoppingCarButton
    /// 店铺
    case shopButton
    /// 预约
    case appointmentButton
}

// MARK: - 底部工具栏事件协议
/// 底部工具栏交互事件回调
protocol GLLiveStreamBottomBarDelegate: AnyObject {
   
    /// 点击聊天消息按钮
    func gl_onInRoomMessageButtonClick()
    /// 点击分享
    func gl_onInRoomShareButtonClick()
    
//    /// 摄像头开关点击
//    func gl_onToggleCameraButtonClick(_ isOn: Bool)
//    /// 麦克风
//    func gl_onToggleMicButtonClick(_ isOn: Bool)
//    /// 切换摄像头点击 (按钮中已实现功能, 所以只处理点击回调)
//    func gl_onGZSwitchCameraButtonClick(_ isFrontFacing: Bool)
    /// 购物车点击
    func gl_shoppingCarButtonClick()
    /// 商铺点击
    func gl_shopButtonClick()
    /// 1v1点击
    func gl_appointmentButtonClick()
    /// 连麦控制按钮点击事件
    /// - Parameters:
    ///   - type: 按钮类型（请求/取消/结束连麦）
    ///   - sender: 事件源按钮
    func gl_coHostControlButtonDidClick(_ type: CoHostControlButtonType, sender: ZegoCoHostControlButton)
}

extension GLLiveStreamBottomBarDelegate {
    func gl_onInRoomMessageButtonClick() { }
    func gl_onInRoomShareButtonClick() {}
    
//    func gl_onToggleCameraButtonClick(_ isOn: Bool) { }
//    func gl_onToggleMicButtonClick(_ isOn: Bool) { }
//    func gl_onGZSwitchCameraButtonClick(_ isFrontFacing: Bool) { }
    func gl_shoppingCarButtonClick() { }
    func gl_shopButtonClick() { }
    func gl_appointmentButtonClick() { }
    func gl_coHostControlButtonDidClick(_ type: CoHostControlButtonType, sender: ZegoCoHostControlButton) { }
}


class GLLiveStreamBottomBar: UIView, ZegoLiveStreamBottomBarType {
    
    var userID: String?
    var config: ZegoUIKitPrebuiltLiveStreamingConfig = GLUIKitPrebuiltLiveStreamingConfig.gl_audience() {
        didSet {
            let glConfig = config as! GLUIKitPrebuiltLiveStreamingConfig
            self.shareButton.isHidden = true
            switch config.role {
            case .host:
                self.barButtons = glConfig.gl_bottomMenuBarConfig.hostButtons
                // self.shareButton.isHidden = false
                
            case .coHost:
                self.barButtons = glConfig.gl_bottomMenuBarConfig.coHostButtons
            case .audience:
                self.barButtons = glConfig.gl_bottomMenuBarConfig.audienceButtons
            }
        }
    }
    
    weak var delegate: GLLiveStreamBottomBarDelegate?
    
    /// 直播状态（0:未开始 1:进行中）
    var liveStatus: String = "0" {
        didSet {
            for button in self.buttons {
                if button is ZegoCoHostControlButton {
                    let coHostControlButton = button as! ZegoCoHostControlButton
                    coHostControlButton.liveStatus = liveStatus
                }
            }
        }
    }
    /// 主播ID
    var hostID: String? {
        didSet {
            for button in self.buttons {
                if button is ZegoCoHostControlButton {
                    let newButton = button as! ZegoCoHostControlButton
                    newButton.hostID = hostID
                }
            }
//            self.messageButton.hostID = hostID
        }
    }
    
    // MARK: - 数据驱动属性
    /// 连麦申请用户列表（更新连麦按钮状态）
    var audienceInviteList: [ZegoUIKitUser]? {
        didSet {
            for button in self.buttons {
                if button is ZegoCoHostControlButton {
                    let coHostControlButton = button as! ZegoCoHostControlButton
                    coHostControlButton.requestList = audienceInviteList
                }
            }
        }
    }
    
    /// 是否处于连麦状态（切换按钮形态）
    var isCoHost: Bool = false {
        didSet {
            for button in self.buttons {
                if button is ZegoCoHostControlButton {
                    let coHostControlButton = button as! ZegoCoHostControlButton
                    coHostControlButton.buttonType = self.isCoHost ? .endCoHost : .requestCoHost
                }
            }
        }
    }
    
    //MARK: - private
    
//    lazy var buttonsStackView: UIStackView = {
//        let stackView = UIStackView()
//        stackView.axis = .horizontal
//        stackView.spacing = self.itemSpace
//        stackView.distribution = .fill
//        stackView.alignment = .fill
//        return stackView
//    }()
    
    /// 适配添加按钮
    private func replayAddAllView() {
        for view in self.subviews {
            view.removeFromSuperview()
        }
        for item in self.buttons {
            self.addSubview(item)
        }
    }
    
    private func removeAllButton() {
        for button in self.buttons {
            button.removeFromSuperview()
        }
    }

    private func setupLayout() {
        self.messageButton.frame = CGRect(x: self.margin, y: UIkitLiveAdaptLandscapeHeight(10), width: itemSize.width, height: itemSize.height)
        
        self.shareButton.frame = CGRect(x: messageButton.frame.maxX + 10, y: UIkitLiveAdaptLandscapeHeight(10), width: itemSize.width, height: itemSize.height)
        
        var rightItemsTotalWidth: CGFloat = 0
        
        for button in self.buttons {
            
            if button is ZegoCoHostControlButton {
                let coHostButton = button as! ZegoCoHostControlButton
                let iconSize = ZegoUIKitLiveStreamIconSetType.bottombar_lianmai.load().size
                let iconWidth = iconSize.width
                var buttonWidth: CGFloat = 0
                let coHostButtonMargin: CGFloat = 16
                if coHostButton.buttonType == .requestCoHost {
                     buttonWidth =  coHostButton.config.translationText.requestCoHostButton.sg.size(width: xScreenW, font: coHostButton.requestCoHostButton.titleLabel!.font!).width + iconWidth + coHostButtonMargin
                    
                } else if coHostButton.buttonType == .cancelCoHost {
                    buttonWidth =  coHostButton.config.translationText.cancelRequestCoHostButton.sg.size(width: xScreenW, font: coHostButton.cancelRequestButton.titleLabel!.font!).width + iconWidth + coHostButtonMargin

                    
                } else if coHostButton.buttonType == .endCoHost {
                    buttonWidth =  coHostButton.config.translationText.endCoHostButton.sg.size(width: xScreenW, font: coHostButton.endCoHostButton.titleLabel!.font!).width + iconWidth + coHostButtonMargin

                }
                coHostButton.layer.masksToBounds = true
                coHostButton.layer.cornerRadius = 18
                coHostButton.frame = CGRect(x: 0, y: 0, width: buttonWidth, height: self.itemSize.height)
            } else {
                button.frame = CGRect(x: 0, y: 0, width: self.itemSize.width, height: self.itemSize.height)
            }
            
            rightItemsTotalWidth += button.bounds.width
        }
        rightItemsTotalWidth += (self.itemSpace * CGFloat((self.buttons.count - 1)))
        
        // 判断是否超过屏幕
        let diff = xScreenW - (self.shareButton.frame.maxX + self.itemSpace + rightItemsTotalWidth + self.margin)
        
        // 证明: 申请连麦的长度长了
        if diff < 0 {
            for button in self.buttons {
                if button is ZegoCoHostControlButton {
                    let originSize = button.bounds.size
                    button.frame = CGRectMake(0, 0, originSize.width + diff, originSize.height)
                    break
                }
            }
        }
        
        var lastView: UIView?
        /// 配置 button 的 size
        for button in self.buttons.reversed() {
            let buttonSize = button.bounds.size
            if let lastV = lastView {
                button.frame = CGRect(x: lastV.frame.minX - itemSpace - buttonSize.width, y: lastV.frame.minY, width: buttonSize.width, height: buttonSize.height)
            } else {
                button.frame = CGRect(x: self.bounds.width - self.margin - buttonSize.width, y: UIkitLiveAdaptLandscapeHeight(10), width: buttonSize.width, height: buttonSize.height)
            }
            lastView = button
        }
        
    }
    
    // MARK: - action
    @objc func messageButtonClick() {
        self.delegate?.gl_onInRoomMessageButtonClick()
    }
    
    
    @objc func shareButtonClick() {
        self.delegate?.gl_onInRoomShareButtonClick()
    }
    
    /// 小黄车点击
    @objc func shoppingCarButtonClick() {
        self.delegate?.gl_shoppingCarButtonClick()
    }
    
    /// 店铺点击
    @objc func shopButtonClick() {
        self.delegate?.gl_shopButtonClick()
    }
    
    /// 申请1v1点击
    @objc func appointmentButtonClick() {
        self.delegate?.gl_appointmentButtonClick()
    }
    

    // MARK: - 私有属性
    
    /// 当前显示的按钮集合
    private var buttons: [UIView] = []
    /// 当前需要显示的按钮类型集合
    var barButtons: [GLLiveStreamBottomBarButtonName] = [] {
        didSet {
            self.removeAllButton()
//            self.moreButtonList.removeAll()
            self.createButton()
            self.setupLayout()
        }
    }
    
    // MARK: - UI 常量
    /// 边距参数（根据横竖屏自适应）
    private let margin: CGFloat = UIkitLiveAdaptLandscapeWidth(16)
    /// 按钮间距
    private let itemSpace: CGFloat = UIkitLiveAdaptLandscapeWidth(8)
    /// 按钮标准尺寸
    let itemSize: CGSize = CGSize.init(width: UIkitLiveAdaptLandscapeWidth(36), height: UIkitLiveAdaptLandscapeWidth(36))
    
    // ZegoUIKitCallIconSetType.icon_message_normal.load()
    /// 消息按钮实例（固定左侧显示）
    private lazy var messageButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(ZegoUIKitCallIconSetType.icon_message_normal.load(), for: .normal)
        button.addTarget(self, action: #selector(messageButtonClick), for: .touchUpInside)
        return button
    }()
    
    /// 分享按钮
    private lazy var shareButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage("ic_share".toImage, for: .normal)
        button.backgroundColor = UIColor(hex: "000000", 0.3)
        button.addRoundedCorners(radius: UIkitLiveAdaptLandscapeWidth(36)*0.5)
        button.addTarget(self, action: #selector(shareButtonClick), for: .touchUpInside)
        return button
    }()
    
    override public init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.clear
        addSubview(messageButton)
        addSubview(shareButton)
        // addSubview(buttonsStackView)
        
        createButton()
        setupLayout()
        // ZegoLiveStreamingManager.shared.addLiveManagerDelegate(self)
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        self.setupLayout()
    }

    
    private func createButton() {
        self.buttons.removeAll()
        var index = 0
        
        func addButtons(button: UIView) {
            self.buttons.append(button)
            self.addSubview(button)
        }
        
        for item in self.barButtons {
            index = index + 1
            
            switch item {
            case .coHostControlButton:
                let coHostButton: ZegoCoHostControlButton = ZegoCoHostControlButton(frame: CGRectZero, translationText: self.config.translationText)
                coHostButton.config = self.config
                coHostButton.delegate = self
                coHostButton.liveStatus = self.liveStatus
                coHostButton.buttonType = self.isCoHost ? .endCoHost : .requestCoHost
                coHostButton.hostID = self.hostID
                coHostButton.requestList = self.audienceInviteList
                addButtons(button: coHostButton)
                
            case .toggleCameraButton:
                let switchCameraComponent: ZegoToggleCameraButton = ZegoToggleCameraButton()
                switchCameraComponent.delegate = self
                switchCameraComponent.isOn = self.config.turnOnCameraWhenJoining
                switchCameraComponent.userID = userID
                addButtons(button: switchCameraComponent)

            case .toggleMicrophoneButton:
                let micButtonComponent: ZegoToggleMicrophoneButton = ZegoToggleMicrophoneButton()
                micButtonComponent.userID = userID
                micButtonComponent.isOn = self.config.turnOnMicrophoneWhenJoining
                addButtons(button: micButtonComponent)

            case .switchCameraButton:
                let button: ZegoSwitchCameraButton = ZegoSwitchCameraButton()
                button.iconFrontFacingCamera = ZegoUIIconSet.iconCameraFlip
                button.iconBackFacingCamera = ZegoUIIconSet.iconCameraFlip
                addButtons(button: button)
                
            case .shoppingCarButton:
                let shoppingCarButton: UIButton = createNormalButton(imageNamed: "ic_shoppingCar", action: #selector(shoppingCarButtonClick))
                addButtons(button: shoppingCarButton)
                
            case .shopButton:
                let shopButton: UIButton = createNormalButton(imageNamed: "ic_shop", action: #selector(shopButtonClick))
                addButtons(button: shopButton)
                
            case .appointmentButton:
                let appointmentButton: UIButton = createNormalButton(imageNamed: "ic_appointment", action: #selector(appointmentButtonClick))
                addButtons(button: appointmentButton)

            }
            
        }
        
    }
    
    /// 创建默认点
    fileprivate func createNormalButton(imageNamed: String, action: Selector) -> UIButton {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: imageNamed), for: .normal)
        button.addTarget(self, action: action, for: .touchUpInside)
        return button
    }
}

extension GLLiveStreamBottomBar: ZegoToggleCameraButtonDelegate, ToggleMicrophoneButtonDelegate, GZSwitchCameraButtonDelegate, ZegoCoHostControlButtonDelegate {
    
//    func onToggleCameraButtonClick(_ isOn: Bool) {
//        self.delegate?.gl_onToggleMicButtonClick(isOn)
//    }
//    
//    func onToggleMicButtonClick(_ isOn: Bool) {
//        self.delegate?.gl_onToggleMicButtonClick(isOn)
//    }
    
//    func onGZSwitchCameraButtonClick(_ isFrontFacing: Bool) {
//        self.delegate?.gl_onGZSwitchCameraButtonClick(isFrontFacing)
//    }
    
    func coHostButtonTypeDidChange() {
        self.setupLayout()
    }
    
    // MARK: 连麦按钮事件
    func coHostControlButtonDidClick(_ type: CoHostControlButtonType, sender: ZegoCoHostControlButton) {
        self.delegate?.gl_coHostControlButtonDidClick(type, sender: sender)
    }
}
